package com.linkoog.devtools.icon_viewer;

import com.intellij.ide.IconProvider;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiFileSystemItem;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.io.IOException;

public class ImageIconProvider extends IconProvider implements DumbAware {


    @Override
    public @Nullable Icon getIcon(@NotNull PsiElement element, int flags) {
        PsiFile containingFile = element.getContainingFile();
        if (isValidImagePath(containingFile)) {
            final VirtualFile canonicalFile = containingFile.getVirtualFile().getCanonicalFile();
            final String fileName = containingFile.getName();
            ImageToIconConverter converter = ImageConverterFactory.create(fileName);
            if (converter != null) {
                try {
                    return converter.convert(canonicalFile, canonicalFile.getCanonicalPath());
                } catch (IOException e) {
                    //LOG.warn(e.message)
                }
            }
        }
        return null;
    }


    private Boolean isValidImagePath(PsiFileSystemItem containingFile){
        if (containingFile == null) return false;

        final VirtualFile virtualFile = containingFile.getVirtualFile();
        if (virtualFile == null) return false;

        final VirtualFile canonicalFile = virtualFile.getCanonicalFile();
        if (canonicalFile == null) return false;

        final String canonicalPath = virtualFile.getCanonicalPath();
        if (canonicalPath == null) return false;

        return !canonicalPath.contains(".jar");
    }
}
